package org.csu.mypetstoreback.controller;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstoreback.domain.Account;
import org.csu.mypetstoreback.domain.Product;
import org.csu.mypetstoreback.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@SessionAttributes("accountList")
public class AccountController {

    @Autowired
    private AccountService accountService;

    // 日志
    //private final Logger logger = LoggerFactory.getLogger(accountController.class);


    @GetMapping("/account/account")
    public String viewBuyers(Model model){
        //logger.info("进入买家信息页面");
        List<Account> accountList = accountService.getAccounts();
        model.addAttribute("accountList", accountList);
        System.out.println(accountList.get(0).getUsername());

        return "account/account";
    }

    //修改用户信息
    @PostMapping("/account/accountChange")
    public String accountChange(Account account){
        accountService.updateAccount(account);
        return "redirect:/account/account";
    }

    //删除用户信息
    @GetMapping("/account/accountDelete")
    public void deleteProduct(String accountname, HttpServletResponse response) throws IOException {
        Account account = new Account();
        account.setUsername(accountname);
        accountService.deleteAccount(account);
        PrintWriter out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();
    }

    //搜索查询用户信息
    @PostMapping("/account/accountSearch")
    public String getProducts(String keyword, Model model){
        System.out.println(keyword);
        List<Account> accountList;
        if(keyword==null) {
            accountList = accountService.getAccounts();
            System.out.println("关键字为空");
        }
        else {
            accountList = accountService.searchAccountList(keyword);
            System.out.println(keyword);
            System.out.println("成功查询");
        }

        model.addAttribute("accountList", accountList);

        return "account/account";

    }

}
